<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="操作时间" prop="operateTime">
        <el-date-picker clearable
          v-model="queryParams.operateTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="就诊卡号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入就诊卡号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleUpdate"
          v-hasPermi="['system:zyconsume:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:zyconsume:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkedZyrecharge" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="住院号" align="center" prop="zyid" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="业务类型" align="center" prop="bizType" />
      <el-table-column label="收费总数" align="center" prop="feesum" />
      <el-table-column label="支付方式" align="center" prop="payType" />
      <el-table-column label="支付金额" align="center" prop="amount" />
      <el-table-column label="支付状态" align="center" prop="payStatus" >
        <template #default="scope">
          <span :style="{ color: scope.row.payStatus === '已支付' ? 'green' : scope.row.payStatus === '未支付' ? 'red' : 'inherit' }">
            {{ scope.row.payStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:zyconsume:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:zyconsume:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门诊充值记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-divider content-position="center">患者信息</el-divider>
      <el-form ref="zyconsumeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-select v-model="form.patientName" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-input v-model="zjlx" disabled/>
        </el-form-item>
        <el-form-item label="微信昵称">
          <el-input v-model="wxnc" disabled/>
        </el-form-item>
        <el-form-item label="就诊地址">
          <el-input v-model="jzrdz" disabled/>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="id">
          <el-input v-model="form.id" placeholder="请输入就诊卡号" disabled/>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="zjhm" disabled/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="sj" disabled/>
        </el-form-item>
        <div class="avatar-uploader">
          <!-- 文本内容 -->
          <span class="text">患者头像</span>

          <!-- 圆形相框 -->
          <div
              class="avatar-frame"
              @click="triggerFileInput"
          >
            <!-- 显示上传的头像或默认空白 -->
            <img
                v-if="avatarUrl"
                :src="avatarUrl"
                alt="用户头像"
                class="avatar-image"
            />
            <div v-else class="empty-frame">
            </div>

            <!-- 隐藏的文件输入 -->
            <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                accept="image/*"
                style="display: none;"
            />
          </div>
        </div>

        <el-form-item label="关系" style="padding-top: 20px">
          <el-input v-model="gx"/>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">就诊信息</el-divider>
      <el-form ref="zyconsumeRef" :model="form1"  label-width="80px">
        <el-form-item label="预约id" prop="patientId">
          <el-select v-model="form1.id" placeholder="请选择预约信息" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in appointments" :key="index" :value="item.id"
                       :label="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊号">
          <el-input v-model="form1.zyid"  clearable >
          </el-input>
        </el-form-item>
        <el-form-item label="就诊医院">
          <el-input v-model="form1.hospital"  clearable disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="医院地址">
          <el-input v-model="form1.hospitalAddress" placeholder="请选择医院地址" clearable disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="就诊科室">
          <el-input v-model="form1.department" placeholder="请选择就诊科室" clearable disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="就诊医生">
          <el-input v-model="form1.doctorId" placeholder="请选择就诊医生" clearable disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="医生职称" >
          <el-input v-model="form1.doctorTitle" placeholder="请选择医生职称" clearable disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-input v-model="bizType" placeholder="请输入业务类型" />
        </el-form-item>
        <el-form-item label="费用类型" prop="payType">
          <el-input v-model="form.payType" placeholder="请输入费用类型" />
        </el-form-item>
        <el-form-item label="费用明细">
        </el-form-item>
        <div class="bottom">
          <table class="fee-table">
            <thead>
            <tr>
              <th>序号</th>
              <th>项目名称</th>
              <th>单价（元）</th>
              <th>数量</th>
              <th>小计（元）</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in feeList" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.price }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ item.subtotal }}</td>
            </tr>
            </tbody>
          </table>
        </div>

        <el-divider content-position="center">订单信息</el-divider>
        <el-form ref="zyconsumeRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="操作时间" prop="operateTime">
            <el-date-picker clearable
                            v-model="form.operateTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择操作时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
          </el-form-item>
          <el-form-item label="支付金额" prop="amount">
            <el-input v-model="form.amount" placeholder="请输入支付金额" disabled />
          </el-form-item>
          <el-form-item label="支付方式" prop="payType">
            <el-input v-model="payType" placeholder="请输入支付方式" />
          </el-form-item>
          <el-form-item label="卡内余额" prop="balance">
            <el-input v-model="form.balance" placeholder="请输入卡内余额" disabled/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="input" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="支付状态" prop="status">
            <el-radio-group v-model="form.payStatus">
              <el-radio
                  v-for="(item, index) in status"
                  :key="index"
                  :label="item.label"
              >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Zyconsume">
import { listZyconsume, getZyconsume, delZyconsume, addZyconsume, updateZyconsume } from "@/api/system/zyconsume"
import {getDepartmentNames} from "@/api/system/departments"
import {listDoctors,getDoctors} from "@/api/system/doctors"
import {listHospitals} from "@/api/system/hospitals"
import {ref, watch} from "vue";
import { listPatients,getPatients,updatePatients} from "@/api/system/patients.js"
import {getAppointments, listAppointments} from "@/api/system/appointments.js";

const { proxy } = getCurrentInstance()

const zyconsumeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const doctorsList = ref([])
const doctorsListzc = ref([])
const ids = ref([])
const checkedZyrecharge = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const gx = ref('本人')
const zjlx = ref('身份证号')
const wxnc = ref('七尾Sam')
const bizType= ref('住院')
const jzrdz = ref('北京市朝阳区**路**号**小区')
const zjhm = ref('371890199507070909')
const sj = ref('15678900988')
const jzyy=ref('北京市第一人民医院/东院')
const yydz=ref('北京市大兴区**路990号')
const jzks=ref('消化内科-门诊3楼东区501')
const jzys=ref('赵马')
const yszc=ref('主任医师')
const payType= ref('微信支付')
const patientid= ref('')
const checkedFeeRecords = ref([])
const fileInput = ref(null);
const avatarUrl = ref('');
const input =   ref('')
const departmentOptions = ref([]);
const hname= ref([]);
const haddress= ref([]);
const patientsList= ref([])
const form1= ref({})
const appointments= ref([])
const balance= ref(0)
const doctormoney= ref(0)
const feeList = ref([
  { name: '雷梦罗布片', price: 50.00, quantity: 2, subtotal: 100.00 },
  { name: '阿司匹林肠溶片', price: 40.00, quantity: 2, subtotal: 80.00 },
  { name: '雷梦罗布片', price: 50.00, quantity: 2, subtotal: 100.00 },
  { name: '阿司匹林肠溶片', price: 40.00, quantity: 2, subtotal: 80.00 }
]);
const status = ref([{
  "label": "未支付",
  "value": "未支付"
}, {
  "label": "已支付",
  "value": "已支付"
}])
// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 创建文件URL并显示
    avatarUrl.value = URL.createObjectURL(file);

    // 这里可以添加实际上传逻辑
    // uploadAvatar(file);
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    operateTime: null,
    orderNo: null,
    patientName: null,
    source: null,
    bizType: null,
    feesum: null,
    payType: null,
    amount: null,
    payStatus: null,
    balance: null,
    ifok:null
  },
  rules: {
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
watch(() => form.value.patientName, (newValue, oldValue) => {
  if (typeof newValue=="number") {
    getPatients(newValue).then(async response => {
      patientid.value = newValue
      wxnc.value = response.data.wechatNickname
      jzrdz.value = response.data.address
      zjhm.value = response.data.idCard
      sj.value = response.data.phone
      form.value.balance = response.data.cardBalance
      form.value.id=response.data.cardNo
      queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        patientId: patientid.value
      }
      await listAppointments(queryParams.value).then(response => {
        appointments.value = response.rows
        if (appointments.value.length===0){
          form1.value.id=""
          form1.value= {}
        }
      })
    });
  }
})
watch(() => form1.value.id, async (newValue) => {
  if (!newValue) return;

  const appointmentResponse = await getAppointments(newValue);
  const appointmentData = appointmentResponse.data;

  // 保留响应式：合并新数据到 form1.value
  Object.assign(form1.value, {
    ...appointmentData,
    doctorId: undefined,
    amount: undefined,
  });

  // 计算费用并更新（同时同步到 form.value）
  if (appointmentData.doctorId) {
    const doctorResponse = await getDoctors(appointmentData.doctorId);
    form1.value.doctorId = doctorResponse.data.name;
    form1.value.amount = doctorResponse.data.bookingFee + 360;
    form.value.amount = form1.value.amount; // 同步到表单数据
  }
});
// /** 查询患者基本信息列表 */
function getPatients1() {
  listPatients(queryParams.value).then(response => {
    // for (var i = 0; i < response.rows.length; i++){
    //   zyconsumeList.value[i].patientName = response.rows[i].name
    //   console.log(zyconsumeList.value[i].patientName)
    // }
    patientsList.value = response.rows
  })
}


/** 查询住院消费记录列表 */
async function getList() {
  loading.value = true
  await listZyconsume(queryParams.value).then(async response => {
    checkedZyrecharge.value = response.rows
    total.value = response.total
    loading.value = false
    // 使用Promise.all处理所有异步请求
    await Promise.all(checkedZyrecharge.value.map(async (item, index) => {
      const patientData = await getPatients(item.patientName);
      checkedZyrecharge.value[index].patientName = patientData.data.name;
    }));
  })
  // await listAppointments(queryParams.value).then(response => {
  //   appointments.value = response.rows
  // })
  getPatients1()
}
function getDoctors1(){
  listDoctors(queryParams.value).then(response => {
    doctorsList.value = response.rows.map(item => item.name);
    doctorsListzc.value = response.rows.map(item => item.title);

  })
}
function getHospitals(){
  listHospitals(queryParams.value).then(response => {
    hname.value = response.rows.map(item => item.name)
    haddress.value = response.rows.map(item => item.address);
  })
}
getHospitals()
// 获取科室列表
function getDepartments() {
  getDepartmentNames().then(response => {
    departmentOptions.value = response.data
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    operateTime: null,
    orderNo: null,
    patientName: null,
    zyid: null,
    source: null,
    bizType: null,
    feesum: null,
    payType: null,
    amount: null,
    payStatus: null,
    balance: null,
    id: null,
    appoimtmentid: null,
  }
  zyrechargeList : []
  proxy.resetForm("zyconsumeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.zyid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加住院消费记录"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  if (row.zyid) {
    reset()
    const _zyid = row.zyid || ids.value
    getZyconsume(_zyid).then(async response => {
      let a = await getAppointments(row.appoimtmentid)
      form1.value = a.data
      patientid.value = a.data.patientId
      queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        patientId: patientid.value
      }
      await listAppointments(queryParams.value).then(response => {
        appointments.value = response.rows
      })
      console.log(await (await getAppointments(row.appoimtmentid)).data)
      form1.value.doctorId = (await getDoctors(await (await getAppointments(row.appoimtmentid)).data.doctorId)).data.name
      doctormoney.value = (await getDoctors(await (await getAppointments(row.appoimtmentid)).data.doctorId)).data.bookingFee
      form.value = response.data
      form.value.amount=doctormoney.value+360
      // form.value.patientName=row.patientName
      getPatients(form.value.patientName).then(response => {
        // form.value.patientName = response.data.name
        zjhm.value = response.data.idCard
        sj.value = response.data.phone
        wxnc.value = response.data.wechatNickname
        jzrdz.value = response.data.address
        form.value.balance = response.data.cardBalance
      })
      // zyrechargeList.value = response.data.zyrechargeList
      open.value = true
      title.value = "修改住院消费记录"
      form.value.patientName = row.patientName
    })
  } else {
    reset()
    appointments.value = []
    open.value = true
    wxnc.value = ""
    jzrdz.value = ""
    zjhm.value = ""
    sj.value = ""
    form1.value = {}
    patientid.value = ""
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["zyconsumeRef"].validate(async valid => {
    console.log(form.value)
    console.log(patientid.value)
      if (valid) {
        if (form.value.zyid != null) {
          if(form.value.ifok===0&&form.value.payStatus==="已支付") {
            if(form.value.amount>form.value.balance&&form.value.payStatus==="已支付"){
              proxy.$modal.msgSuccess("余额不足无法支付,请修改支付金额或选择“未支付”")
            }else{
              form.value.ifok = 1
              form.value.balance = form.value.balance - form.value.amount
              let a=await getPatients(patientid.value)
              a.data.cardBalance = form.value.balance
              await updatePatients(a.data)
              form.value.patientName = patientid.value
              updateZyconsume(form.value).then(response => {
                proxy.$modal.msgSuccess("修改成功")
                open.value = false
                getList()
              })
              patientid.value = ""
            }
          }else {
            form.value.patientName = patientid.value
            updateZyconsume(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功")
              open.value = false
              getList()
            })
            patientid.value = ""
          }
        }else {
          form.value.zyid=form1.value.zyid
          form.value.appoimtmentid = form1.value.id
          form.value.bizType = "住院"
          form.value.payType ="微信"
          addZyconsume(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
            patientid.value = ""
          })
        }
      }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _zyids = row.zyid || ids.value
  proxy.$modal.confirm('是否确认删除住院消费记录编号为"' + _zyids + '"的数据项？').then(function() {
    return delZyconsume(_zyids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 住院充值记录序号 */
function rowZyrechargeIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 住院充值记录添加按钮操作 */
function handleAddZyrecharge() {
  let obj = {}
  obj.operateTime = ""
  obj.orderNo = ""
  obj.patientName = ""
  obj.source = ""
  obj.bizType = ""
  obj.payType = ""
  obj.amount = ""
  obj.payStatus = ""
  obj.balance = ""
  // zyrechargeList.value.push(obj)
}

/** 住院充值记录删除按钮操作 */
function handleDeleteZyrecharge() {
  if (checkedZyrecharge.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的住院充值记录数据")
  } else {
    const zyrecharges = zyrechargeList.value
    const checkedZyrecharges = checkedZyrecharge.value
    zyrechargeList.value = zyrecharges.filter(function(item) {
      return checkedZyrecharges.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleZyrechargeSelectionChange(selection) {
  checkedZyrecharge.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/zyconsume/export', {
    ...queryParams.value
  }, `zyconsume_${new Date().getTime()}.xlsx`)
}

getList()
getDepartments()
getDoctors1()
</script>
<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 10px;
}

.text {
  font-size: 15px;
  padding-right: 32px;
  padding-left: 10px;
  font-weight: 600;

}

.avatar-frame {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  background-color: #E4EFFE;
}


.empty-frame {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #ccc;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.fee-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 5px;
}
.fee-table th,
.fee-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
}
.fee-table th {
  background-color: #E8F2FF;
  color: #666;
  font-size: 14px;
  font-weight: normal;
}

</style>